<template>
  <el-dialog
    v-model="visible"
    :title="title"
    destroy-on-close
    width="42vw"
    @close="handleCancel"
  >

    <el-form
      ref="formRef"
      :model="formState"
      :rules="Rules"
      label-width="100px"
      class="doc-dia"
    >
      <el-form-item label="上传文档" prop="defaultFileList">
        <el-upload
          :disabled='props.dialogType==="edit"'
          name="uploadFile"
          drag
          :limit="1"
          :accept="acceptTypes"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :on-error="handleError"
          :on-preview="handlePreview"
          :file-list="defaultFileList"
        >
          <div class="el-upload__text">
            <em>点击上传 </em>或拖拽文件到此区域上传
            <div class="el-upload__tip">
              <p>备注：</p>
              <p>1、支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg、zip、dwg等格式文件,文件大小不得大于20M；</p>
              <p>2、模型类文件支持上传的格式类型包括：fbx、stl、obj、rvm、bmv、rfa、dgn、dwg、rvt、skp。</p>
              <p>3、一次仅支持上传一个文件</p>
            </div>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item
        label="文档名称"
        placeholder="请输入文档名称"
        prop="documentName"
      >
        <el-input
          v-model="formState.documentName"
          disabled
        />
      </el-form-item>

      <el-form-item
        label="文件类型"
        placeholder="请输入文件类型"
        prop="docTypeName"
      >
        <el-input
          v-model="formState.docTypeName"
          disabled
        />
      </el-form-item>

      <el-form-item
        label="文档类型"
        placeholder="请选择文档类型"
        prop="documentTypeObj"
      >
        <el-select
          clearable
          class="width-custom100"
          v-model="documentTypeObj"
          value-key="dicCode"
        >
          <el-option
            v-for="item in documentTypeList"
            :label="item.dicValue"
            :key="item.dicCode"
            :value="item"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSure">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive,onMounted,defineProps,defineEmits } from "vue";
import { useRouter } from "vue-router";
import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";
import { download } from "/@/utils/download";
import * as api from "/@/api/document";
import { acceptTypes, uploadUrl,docTypesMatch } from "../types";
const formRef = ref<HTMLFormElement | null>(null) as any;
const props = defineProps({
  title: {
    type: String,
    default: "添加文档"
  },

  dialogType: {
    type: String,
    default: "add"
  },

  fileItem:{
    type: Object,
    default: ()=>{}
  }
});
const documentTypeList = ref([])
let defaultFileList = ref([]);
const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};
const emit = defineEmits(["cancel","submit"]);
const title = ref("添加文档");
const dialogType = ref("add");
const router = useRouter();
let formState = reactive({
  docSuffix:"",               //文件后缀名
  docTypeName: "",            //文件类型名称
  docType:"",                 //文件类型
  documentAttachmentArr:[],
  documentTypeName:"",        //文档类型名称
  documentTypeCode:"",        //文档类型编码
  documentName: "",           //文档名称
  moduleType: "1",
  projectManageId: "",
  projectName: "",
  projectTypeCode: "",
  remarks: ""
});

const documentTypeObj = ref({
  dicValue:"",
  dicCode:''
});
const visible = ref(true);
const Rules = {
  documentName: [
    { required: true, message: "请输入文档名称", trigger: "blur" }
  ],
  docTypeName: [
    { required: true, message: "请输入文件类型", trigger: "blur" }
  ],
  // documentTypeObj: [
  //   { required: true, message: "请选择文档类型", trigger: "change" }
  // ],
  // defaultFileList: [
  //   { required: true, message: "请上传文档", trigger: "change" }
  // ]
};

const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return;
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

if(props.title){
  title.value = props.title;
  dialogType.value = props.dialogType;
}
if(dialogType.value === "edit"){
  formState = Object.assign(props.fileItem);
  documentTypeObj.value.dicValue = props.fileItem.documentTypeName;
  documentTypeObj.value.dicCode = props.fileItem.documentTypeCode;
  defaultFileList.value = onInitFileList(formState.documentAttachmentArr);
}

const handleCancel = () => {
  emit("cancel");
};

const handleSure = async () => {
  const isValid = await new Promise(resolve =>
    formRef.value.validate(resolve)
  );
  if (isValid) {
    formState.documentAttachmentArr = onFilterFileData(defaultFileList.value);
    formState.documentTypeName = documentTypeObj.value.dicValue;
    formState.documentTypeCode = documentTypeObj.value.dicCode;
    formState.projectManageId =  storageLocal.getItem("projectInfo")?.id
    formState.projectName=  storageLocal.getItem("projectInfo")?.name
    formState.projectTypeCode=  storageLocal.getItem("projectInfo")?.projectTypeCode
    emit("submit", formState);
  }
};

/* 上传 -- start */
// const acceptTypes = Object.values(FileTypes).join(",");
// const uploadUrl =
//   import.meta.env.VITE_BASE_URL + "/snow-admin/common/file/upload";
// const uploadHeaders = {
//   Authorization: storageLocal.getItem("info")?.accessToken
// };

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
  formState.documentName =  "";
  formState.docTypeName =  "";
  formState.docType =  "";
  formState.docSuffix = ""
};

const handleChange = (file, fileList) => {
  defaultFileList.value = fileList;
  formRef.value.clearValidate();
  formState.documentName =  file.name;
  formState.docType =  docTypesMatch(file.name.split(".")[1]).key;
  formState.docTypeName =  docTypesMatch(file.name.split(".")[1]).name;
  formState.docSuffix = file.name.split(".")[1]
};

const handlePreview = file => {
  console.log(file, "file");
  if (file?.response?.code !== 200 || !file?.response?.data) return;
  download(file?.response?.data);
};

const handleError = err => {
  let myError = err.toString(); //转字符串
  myError = myError.replace("Error: ", ""); // 去掉前面的" Error: "
  myError = JSON.parse(myError); //转对象
  myError?.message && NotifMessage.error(myError?.message);

  if (myError?.body?.code && [401, 403].includes(myError?.body?.code)) {
    myError?.body?.message && NotifMessage.error(myError?.body?.message);
    router.push("/login");
    storageLocal.removeItem("info");
  }
};

const onFilterFileData = (list: any[]) => {
  if (!list || !list.length) return;
  const newFileData = list.map(item => {
    // if (item.status === "success") {
    return item.response.data;
    // }
  });
  return newFileData;
};
/* 上传 -- end */

// 获取文档类型
const initDoucumentTypeList = async () => {
  try {
    const { data } = await api.postDictList({dicType: "thd_document_type"});
    documentTypeList.value = data;
  } catch (err) {
    console.log(err);
  }
};

onMounted(() => {
  initDoucumentTypeList();
})



</script>
<style scoped lang="scss">
.doc-dia {
  :deep .el-upload{
    width: 100%;
  }
  :deep .el-upload-dragger{
    width: 100%;
    height: auto;
    padding: 20px 0 20px 20px;
  }
  .el-upload__tip{
    text-align: left;
    line-height: 20px;
    font-size: 10px;
    color:#999;
  }
  .width-custom100{
    width:100%
  }
}
</style>
